package com.wing.web.intercepter;

import cn.hutool.core.util.StrUtil;
import com.nimbusds.jose.JWSObject;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Enumeration;

@Component
@Slf4j
public class FeignIntercepter implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        log.info("----------------------feign intercepter start--------------------");
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes==null){
            return;
        }
        HttpServletRequest request=servletRequestAttributes.getRequest();
        log.info("-------------------------feign intercepter url:{}",request.getRequestURL().toString());
        String token=request.getHeader("Authorization");
        log.info("---------------------feign intercepter token:{}",token);
        if (StringUtils.isBlank(token)){
            /** 用于对外api等一些不需要token的情况 **/
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    log.info("-------------------------feign name:{}",name);
                    String values = request.getHeader(name);
                    log.info("-------------------------feign values:{}",values);
                    template.header(name, values);
                }
            }
            /** 用于对外api等一些不需要token的情况 **/
            return;
        }
        if (StringUtils.isNotBlank(token)){
            token=token.substring("Bearer ".length(),token.length());
        }
        String payload = "";
        try{
            payload=StrUtil.toString(JWSObject.parse(token).getPayload());
            payload=URLEncoder.encode(payload, "UTF-8");
        }catch (Exception e){
            log.error("parse token fail",e);
        }
        template.header("feign-aes", "true");
        template.header("payload", payload);
        log.info("------------------------feign intercepter payload:{}",payload);
    }
}
